package com.application.module_chat2.activity;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;

import com.alibaba.android.arouter.facade.annotation.Autowired;
import com.alibaba.android.arouter.facade.annotation.Route;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.application.module_chat2.R;
import com.application.module_chat2.adapter.ChatAdapter;
import com.application.module_chat2.presenter.ChatPresenter;
import com.application.module_chat2.view.ChatView;
import com.application.module_chat2.widgth.ChatInput;
import com.application.mylibrary.base.mvp.BaseMvpActivity;
import com.application.mylibrary.utils.LogUtils;
import com.application.mylibrary.widget.keybord.ChatBottomPanel;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import io.rong.imlib.model.Message;

@Route(path = "/module_chat/ChatActivity")
public class ChatActivity extends BaseMvpActivity<ChatView, ChatPresenter>
        implements ChatView, ChatBottomPanel.BottomInputBackListener, View.OnClickListener {

    private ChatInput chatInput;
    private RecyclerView chatList;
    private ChatAdapter adapter;
    @Autowired(name="uId")
    public String uId;
    private View newMessage;
    private SwipeRefreshLayout mSlImChat;

    @Override
    public void beforeInit() {
        if (TextUtils.isEmpty(uId)) {
            uId = "2";
        }
    }

    @Override
    public int getLayoutId() {
        return R.layout.activity_chat;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        loadData();
    }

    private void loadData() {
        if (getPresenter() != null) {
            getPresenter().getMessageHistory(messageId);
        }
    }

    @Override
    public boolean registerEventBus() {
        return true;
    }
    private int messageId =-1;
    private boolean userHasAction;
    private boolean autoScroll;

    public void initView() {
        chatInput = new ChatInput(new WeakReference<Activity>(this));
        chatInput.setInputListener(this);
        chatList = ( findViewById(R.id.lv_chat));
        chatList.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ChatAdapter(new ArrayList());
        chatList.setAdapter(adapter);
        newMessage = findViewById(R.id.text_new_message);
        newMessage.setOnClickListener(this);
        mSlImChat = ( findViewById(R.id.chat_refresh));
        mSlImChat.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                if (getPresenter()!=null) {
                    getPresenter().getMessageHistory(messageId);
                }
            }
        });
        adapter.setOnItemChildLongClickListener(new BaseQuickAdapter.OnItemChildLongClickListener() {
            @Override
            public boolean onItemChildLongClick(BaseQuickAdapter adapter, View view, int position) {
                return false;
            }
        });
        chatList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                if (newState == RecyclerView.SCROLL_STATE_IDLE && userHasAction) {
                    LinearLayoutManager manager = (LinearLayoutManager) recyclerView.getLayoutManager();
                    int lastposition = manager.findLastVisibleItemPosition();
                    if (lastposition == manager.getItemCount() - 1) {
                        resetState();
                    } else {
                        autoScroll = false;
                    }
                } else {
                    autoScroll = false;
                }
            }
        });
        chatList.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == MotionEvent.ACTION_DOWN) {
                    userHasAction = true;
                    //输入框消失
                    chatInput.reset();
                }
                return false;
            }
        });


    }



    private void resetState() {
        autoScroll = true;
        userHasAction = false;
        newMessage.setVisibility(View.GONE);
    }

    public void scrollToBottom() {
        if (autoScroll) {
            int count = adapter.getItemCount() - 1;
            if (count > 0) {
                chatList.scrollToPosition(count);
            }
        } else {
            // 显示 新消息 提示
            newMessage.setVisibility(View.VISIBLE);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void receiverMessage(Message message) {
        //如果发送者的id和传进的一样的话  就接受
        if (message.getSenderUserId().equals(uId)) {
            if (getPresenter()!=null) {
                getPresenter().receiverMessage(message);
            }
        }
    }

    @Override
    public ChatView createView() {
        return this;
    }

    @Override
    public ChatPresenter createPresenter() {
        return new ChatPresenter(uId);
    }

    @Override
    public void input(String s) {
        if (getPresenter() != null) {
            getPresenter().sendTextMessage(s);
        }
    }

    @Override
    public void funOpen() {
        if (autoScroll) {
            int count = adapter.getItemCount() - 1;
            if (count > 0) {
                chatList.scrollToPosition(count);
            }
        }
    }

    @Override
    public void funClose() {

    }

    @Override
    public void receiverMessage(ChatAdapter.ChatBean bean) {
        if (bean.getMsgType() < 0) {
            return;
        }
        if (adapter != null) {
            adapter.addMessage(bean);
            int count = adapter.getItemCount() - 1;
            if (count >= 0) {
                adapter.notifyItemInserted(count);
            }
            scrollToBottom();
        }
    }

    @Override
    public void upMessage(ChatAdapter.ChatBean bean) {

    }

    @Override
    public void addMessageList(List<ChatAdapter.ChatBean> beans) {
        if (beans.size() > 0) {
            adapter.addDataBeanList(beans);
            if (messageId == -1) {
                scrollToBottom();
            } else {
                int count = beans.size() - 1;
                if (count > 0) {
                    chatList.scrollToPosition(count);
                }
            }
            LogUtils.i("adapter.size====" + adapter.getItemCount());
            messageId = beans.get(0).getMessageId();
        } else {
            mSlImChat.setEnabled(false);
        }

        mSlImChat.setRefreshing(false);
    }


    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.text_new_message) {
            int count = adapter.getItemCount() - 1;
            if (count > 0) {
                chatList.scrollToPosition(count);
            }
            resetState();
        }
    }
}
